import { func } from "uview-plus/libs/function/test"
import { AddressUtils } from "./addressUtils"
import { CategoryUtils } from "./categoryUtils"
import { UserUtils } from "./userUtils"

const baseUrl = "http://192.168.1.82:8080/app"

// 检查后端返回的 Result{data: any, message: str, code: int}
export function checkResult(result) {
	if( typeof result === "string" ) result = JSON.parse(result)
	if (result.code != 200) {
		uni.showToast({
			title: result.message,
			icon: "error"
		})
		throw new Error()
	}
	return result.data
}

// 检查请求是否成功，成功则返回 data、否则报错
export function checkResponse(response) {
	if (response.statusCode == 401) {
		uni.showToast({title: "登录失效，请重新登录", icon: "none"})
		logout()
		throw new Error()
	}
	return response.data
}

export function checkResultPage(response) {
	let resultPage = checkResponse(response)
	if( typeof resultPage === "string" ) resultPage = JSON.parse(resultPage)
	if (resultPage.code != 200) {
		uni.showToast({
			title: resultPage.message,
			icon: "error"
		})
		throw new Error()
	}
	return resultPage
}

export function checkError(error) {
	// 如果是服务器挂了
	if (error.errMsg.includes("fail")) 
		uni.showToast({
			title: "服务器无响应，请稍后重试", 
			icon: "error",
		})
	throw error
}

export function check(response) {
	return checkResult(checkResponse(response))
}

export function getRequest(config) {	
	config.url = baseUrl + config.url
	if (config.header != undefined) {
		config.header = {
			...config.header, 
			token: UserUtils.getToken()
		}
	} 
	else {
		config = {
			...config, 
			header: {
				token: UserUtils.getToken()
			}
		}
	}
	return config
}

export function formatPrice(price) {
    if (price >= 1000000) return (price / 1000000).toFixed(1) + 'M'
	else if (price >= 1000) return (price / 1000).toFixed(1) + 'K'
    else return price.toFixed(1)
}

export function logout() {
	UserUtils.clear()			// 清空 userinfo
	CategoryUtils.clear()		// 清空 categories
	AddressUtils.clear()		// 清空 address
	
	uni.redirectTo({url: '/pages/login/login'})
}